package com.meihuayishu.backend.config;

import com.meihuayishu.backend.service.AuthService;
import com.meihuayishu.backend.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    private final JwtUtil jwtUtil;
    private final AuthService authService;
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, 
                                    HttpServletResponse response, 
                                    FilterChain filterChain) throws ServletException, IOException {
        
        String authorizationHeader = request.getHeader("Authorization");
        
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7);
            
            try {
                if (authService.validateAccessToken(token)) {
                    String userId = authService.getUserIdFromToken(token);
                    String membershipType = jwtUtil.getMembershipTypeFromToken(token);
                    
                    // 创建认证对象
                    List<SimpleGrantedAuthority> authorities = List.of(
                            new SimpleGrantedAuthority("ROLE_USER")
                    );
                    
                    // 如果是VIP用户，添加VIP权限
                    if (authService.isVipMember(token)) {
                        authorities = List.of(
                                new SimpleGrantedAuthority("ROLE_USER"),
                                new SimpleGrantedAuthority("ROLE_VIP")
                        );
                    }
                    
                    UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(userId, null, authorities);
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 设置认证信息到安全上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    
                    // 将用户ID和会员类型添加到请求属性中，方便控制器使用
                    request.setAttribute("userId", userId);
                    request.setAttribute("membershipType", membershipType);
                }
            } catch (Exception e) {
                log.debug("JWT认证失败: {}", e.getMessage());
                // 认证失败，继续过滤链，让Spring Security处理
            }
        }
        
        filterChain.doFilter(request, response);
    }
    
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        String path = request.getRequestURI();
        // 跳过认证的路径
        return path.startsWith("/api/v1/auth/") ||
               path.startsWith("/api/v1/hexagrams") ||
               path.startsWith("/api/v1/app/config") ||
               path.startsWith("/doc.html") ||
               path.startsWith("/webjars/") ||
               path.startsWith("/swagger-ui/") ||
               path.startsWith("/v3/api-docs") ||
               path.equals("/favicon.ico");
    }
}